<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { z } from 'zod'
import LoadingContainer from '@/components/common/LoadingContainer.vue'
import message from '@/components/common/message'
import { verifyCode, verifyCodeLogin } from '@/request/auth'
import AuthInput from './components/AuthInput.vue'
import VerifyCodeInput from './components/VerifyCodeInput.vue'

const router = useRouter()
const account = ref('')
const isLoading = ref(false)
const isVerifyStage = ref(false)
const verifyCodeRef = ref<InstanceType<typeof VerifyCodeInput> | null>(null)
const accountInput = ref<InstanceType<typeof AuthInput> | null>(null)

// 创建Zod校验模式 - 支持手机号或邮箱
const accountSchema = z.string()
  .min(1, '请输入手机号或邮箱')
  .refine(
    (value) => {
      // 手机号验证
      const phoneRegex = /^1[3-9]\d{9}$/
      // 邮箱验证
      const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
      return phoneRegex.test(value) || emailRegex.test(value)
    },
    {
      message: '请输入有效的手机号或邮箱地址',
    },
  )

// 表单验证状态
const accountValid = ref(false)

// 处理验证错误
function handleValidationError(field: string, _error: string) {
  if (field === 'account')
    accountValid.value = false
}

// 处理验证成功
function handleValidationSuccess(field: string) {
  if (field === 'account')
    accountValid.value = true
}

// 验证所有输入
function validateAllInputs() {
  let isAllValid = true
  if (accountInput.value) {
    const isAccountValid = accountInput.value.forceValidate()
    isAllValid = isAllValid && isAccountValid
  }
  return isAllValid
}

// 发送验证码API调用
async function sendVerifyCode(accountValue: string) {
  return verifyCode({ data: accountValue })
}

// 进入验证码阶段
async function goToVerifyStage() {
  const isValid = validateAllInputs()
  if (!isValid) {
    return
  }
  try {
    isLoading.value = true
    await sendVerifyCode(account.value)
    isVerifyStage.value = true
    message.success('验证码发送成功')
  }
  catch (error: any) {
    message.error(error)
  }
  finally {
    isLoading.value = false
  }
}

// 重新发送验证码
async function handleResendCode() {
  try {
    isLoading.value = true
    await sendVerifyCode(account.value)
    message.success('验证码重新发送成功')
  }
  catch (error: any) {
    message.error(error)
  }
  finally {
    isLoading.value = false
  }
}

// 处理验证码完成
async function handleCodeComplete(code: string) {
  try {
    isLoading.value = true
    const requestData = {
      phone: account.value,
      verificationCode: code,
    }
    const info = await verifyCodeLogin(requestData)
    localStorage.setItem('token', info.access_token)
    message.success('登录成功')
    router.push('/')
  }
  catch (error: any) {
    if (verifyCodeRef.value) {
      verifyCodeRef.value.clearCode()
    }
    message.error(error)
  }
  finally {
    isLoading.value = false
  }
}

function goBackToFirstStep() {
  isVerifyStage.value = false
}
function goBackToPasswordLogin() {
  router.push('/auth')
}
</script>

<template>
  <LoadingContainer :loading="isLoading">
    <div v-if="!isVerifyStage" class="verify-login-container">
      <div class="verify-login-header">
        <h1>验证码登录</h1>
        <p>使用手机号或邮箱验证码快速登录</p>
      </div>

      <div class="verify-login-inputs">
        <AuthInput
          ref="accountInput" v-model="account" type="phone-email" placeholder="请输入手机号或邮箱" :schema="accountSchema"
          @validation-error="(error) => handleValidationError('account', error)"
          @validation-success="() => handleValidationSuccess('account')"
        />
      </div>

      <button class="next-step-button" :disabled="isLoading" @click="goToVerifyStage">
        {{ isLoading ? '发送中...' : '获取验证码' }}
      </button>

      <div class="auth-links">
        <div class="password-login-link">
          <a @click="goBackToPasswordLogin">密码登录</a>
        </div>
        <div class="register-link">
          还没有账号? <a @click="router.push('/auth/register')">立即注册</a>
        </div>
      </div>
    </div>

    <div v-else class="verify-container">
      <VerifyCodeInput
        ref="verifyCodeRef" :phone-number="account" :disabled="isLoading" @complete="handleCodeComplete"
        @resend="handleResendCode"
      >
        <template #back-button>
          <span class="back-icon" @click="goBackToFirstStep">&lt;</span>
        </template>
      </VerifyCodeInput>
    </div>
  </LoadingContainer>
</template>

<style scoped>
.verify-login-header {
  text-align: center;
  margin-bottom: 50px;
}

.verify-login-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
}

.verify-login-header p {
  font-size: 16px;
  color: #666;
}

.verify-login-inputs {
  margin-bottom: 24px;
}

.next-step-button {
  width: 100%;
  height: 50px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 24px;
}

.next-step-button:hover {
  background-color: #40a9ff;
}

.next-step-button:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}

.auth-links {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.password-login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.password-login-link a {
  color: #1890ff;
  text-decoration: none;
  cursor: pointer;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #1890ff;
  text-decoration: none;
  cursor: pointer;
}

.back-icon {
  font-size: 24px;
  cursor: pointer;
}
</style>
